package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor{
    //列表用于保存线程
    private List<Thread> threadList  = new ArrayList<>();
    //用来保存任务的队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100);
    //通过n来指定创建多少个线程
    public MyThreadPoolExecutor(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                //TODO,线程要做的事情就是不断地把任务从任务队列中取出来并执行
                while(true){
                    try {
                        //此处的take带有阻塞功能
                        //如果队列为空,此处的take就会阻塞
                        Runnable runnable=queue.take();
                        //取出一个任务就执行一个任务
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();

        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);

    }
}
public class ThreadDemo8 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor(4);
        for (int i = 0; i <1000; i++) {
            int n = i;
            myThreadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务"+n+"当前线程为"+Thread.currentThread().getName());
                }
            });

        }
    }
}
